package hj212

import (
	"reflect"

	"github.com/funny/link"
	"go.uber.org/zap"

	"gitee.com/whoiszhangben/hj212_recSvc/core/hj212/protocol"
	"gitee.com/whoiszhangben/hj212_recSvc/global"
)

type sessionHandler struct {
	server *Server
}

// HandleSession 消息处理器
func (handler sessionHandler) HandleSession(sess *link.Session) {
	global.GVA_LOG.Info("new session created", zap.Uint64("sessionID", sess.ID()))

	session := newSession(handler.server, sess)
	handler.server.mutex.Lock()
	handler.server.sessions[sess.ID()] = session
	handler.server.mutex.Unlock()

	sess.AddCloseCallback(nil, nil, func() {
		handler.server.handleClose(session)
	})

	for {
		msg, err := sess.Receive()
		if err != nil {
			sess.Close()
			break
		}

		message := msg.(protocol.Message)
		if message.Body == nil || reflect.ValueOf(message.Body).IsNil() {
			continue
		}
		session.message(&message)
		handler.server.dispatchMessage(session, &message)
	}
}
